from django.shortcuts import render

# Create your views here.
# views.py
from .models import BookModel, BookBorrowRecordModel
from .serializers import BookSerializers
from datetime import timedelta
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from django.utils import timezone


class BookWatchView(APIView):
    def get(self, request):
        """
        查询指定书籍情况或全部可借书籍情况
        :param request:
        :return:
        """
        title = request.GET.get('title')
        if title:
            book = BookModel.objects.filter(title=title).first()
            if book:
                ser = BookSerializers(book)
                return Response(ser.data, status=status.HTTP_200_OK)
            return Response({'msg': '查询不到该书籍', 'code': status.HTTP_200_OK})
        else:
            book = BookModel.objects.filter(status=0, is_deleted=False).all()
            ser = BookSerializers(book, many=True)
            return Response({'data': ser.data, 'msg': '成功', 'code': status.HTTP_200_OK})

    def post(self, request):
        """
        书籍录入
        data={
            "title": "疯狂星期四",
            "author": "爱德华",
            "serial_number": "202503070001",
            "publication_date": "2025-03-07",
            "stock":100
            }
        :param request:
        :return:
        """
        data = request.data
        ser = BookSerializers(data=data)
        if ser.is_valid():
            ser.save()
            return Response({'msg': '录入成功', 'code': status.HTTP_200_OK})
        return Response({'msg': ser.errors, 'code': status.HTTP_400_BAD_REQUEST})

    def put(self, request):
        """
        书籍信息修改
        data = {
            "title": "疯狂星期七",
            "author": "爱德华",
            "serial_number": "202503070002",
            "publication_date": "2025-03-08",
            "stock":100
        }
        :param request:
        :return:
        """
        data = request.data
        book = BookModel.objects.filter(serial_number=data.get("serial_number")).first()
        ser = BookSerializers(book, data=data)
        if ser.is_valid():
            ser.save()
            return Response({'msg': '修改成功', 'code': status.HTTP_200_OK})
        return Response({'msg': ser.errors, 'code': status.HTTP_400_BAD_REQUEST})

    def delete(self, request):
        """
        根据书籍编号来进行删除
        :param request:
        :return:
        """
        serial_number = request.GET.get('serial_number')
        book_obj = BookModel.objects.filter(serial_number=serial_number).first()
        if book_obj:
            book_obj.is_deleted = True
            book_obj.save()
            return Response({'msg': '删除成功', 'code': status.HTTP_200_OK})
        return Response({'msg': '查询不到该书籍编号，无法删除', 'code': status.HTTP_200_OK})


class BookBorrowView(APIView):
    def post(self, request):
        """
        用户借书操作
        :param request:
        :return:
        """
        serial_number = request.data.get('serial_number')
        borrower = request.data.get('borrower')
        number = request.data.get('number')
        book_obj = BookModel.objects.filter(serial_number=serial_number).first()
        if not book_obj:
            return Response({'msg': '书籍不存在', 'code': status.HTTP_400_BAD_REQUEST})
        # 判断书籍的库存情况
        if book_obj.stock >= int(number):
            book_obj.stock -= int(number)
            if book_obj.stock == 0:
                book_obj.status = -1
            book_obj.save()
            # 记录借阅信息
            return_date = timezone.now().date() + timedelta(days=30)
            BookBorrowRecordModel.objects.create(book_id=book_obj.id, borrower=borrower,
                                                 return_date=return_date, number=number)
            return Response({'msg': '借阅成功', 'code': status.HTTP_200_OK})
        else:
            return Response({'msg': '当前库存不足，剩余{}本，请重新输入借阅数量'.format(book_obj.stock)})


class BookReturnView(APIView):
    def post(self, request):
        """
        用户归还书籍
        :param request:
        :return:
        """
        serial_number = request.data.get('serial_number')
        borrower = request.data.get('borrower')
        book_obj = BookModel.objects.filter(serial_number=serial_number).first()
        if not book_obj:
            return Response({'msg': '书籍不存在', 'code': status.HTTP_400_BAD_REQUEST})
        borrow_obj = BookBorrowRecordModel.objects.filter(book_id=book_obj.id, borrower=borrower,
                                                          is_return=False).first()
        if not borrow_obj:
            return Response({'msg': '还书失败,不存在借阅记录', 'code': status.HTTP_400_BAD_REQUEST})
        borrow_obj.is_return = True
        borrow_obj.save()

        book_obj.stock += borrow_obj.number
        book_obj.save()
        return Response({'msg': '还书成功', 'code': status.HTTP_200_OK})
